<template>
  <div class="AllotApp-page allotApp-publicStyle">
    <Row :gutter="16">
      <Col span="18" class="table-border">
        <Row :gutter="16">
          <Col span="12" class="table-border" v-for="item in appInfo" :key="item.type">
                <!-- 分配应用 - 标题 -->
            <div class="title">{{ item.label}}</div>
            <div class="allot-app-wrap innerPageTable-box-OneTwo">
              <Input
                  type="text"
                  class="serach-input"
                  :maxlength="30"
                  v-model.trim="item.searchForm.nameOrCode"
                  :placeholder="$t('module.userManage.placeholder.enterAppCodeOrAppName')"
                  clearable
                  @on-enter="item.loadDataFun"
                  @on-clear="item.loadDataFun"
                >
                  <template #append>
                    <Icon type="ios-search" style="cursor: pointer;" @click="item.loadDataFun"/>
                  </template>
                </Input>
                <div class="app-list">
                  <List size="small" v-if="(item.appList && item.appList.length > 0) || item.loading" :loading="item.loading">
                      <ListItem v-for="app in item.appList" :key="app.id" >
                        <Checkbox :disabled="app._disabled" v-model="app._checked" @on-change="item.appSelectChange($event, app)"></Checkbox>
                        <span>
                          {{app.applicationName}} ({{app.applicationCode}})
                        </span>
                      </ListItem>
                  </List>
                  <p v-else style="text-align: center">暂无数据</p>
                </div>
              </div>
          </Col>
        </Row>
      </Col>
      <Col span="6" class="table-border">
      <div class="select-App-list">
        <div class="title">已授权 {{selectAdd.selfBuiltApp.length + selectAdd.thirdPartyApp.length}}项</div>
        <div class="select-app">
          <span class="title">自建应用</span>
          <List size="small" class="self-built-app">
              <ListItem v-for="app in selectAdd.selfBuiltApp" :key="app.id">
                <span class="select-icon"></span>
                <span class="app-name">
                  {{app.applicationName}} ({{app.applicationCode}})
                </span>
              </ListItem>
          </List>
          <span class="title">第三方应用</span>
          <List size="small">
              <ListItem v-for="app in selectAdd.thirdPartyApp" :key="app.id">
                <span class="select-icon"></span>
                <span class="app-name">
                  {{app.applicationName}} ({{app.applicationCode}})
                </span>
              </ListItem>
          </List>
        </div>
      </div>
      </Col>
    </Row>

  </div>
</template>

<script>
// 分配应用
import locales from "./locales.js";
// import valueSetAPI from "@/api/valueSetAPI.js";
import userManageAPI from "@/api/userManageApi";
export default {
  name: "AllotApp",
  mixins: [locales],
  props: {
    selectApp: {
      type: Array,
      default: () => {
        return [];
      }
    },
    appType: {
      type: String,
      default: 'selfBuilt'
    },
    userInfo: {
      type: Object,
        default: () => {
          return {};
      }
    },
    defaultSelectApp: {
      type: Array,
      default: () => {
        return [];
      }
    },
    tenantCodeAndUser: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  data() {
    return {
      // 标识当前是否是搜索查询
      appList: [],
      selectAdd: {
        selfBuiltApp: [],
        thirdPartyApp: []
      },
      appInfo: [
        {
          label: this.$t("module.userManage.selfBuilt"),
          type: 'selfBuilt',
          loading: false,
          appList: [],
          searchForm: {
            nameOrCode: ""
          },
          loadDataFun: () => {
            this.searchData('selfBuilt', 0)
          },
          appSelectChange: ($event, app) => {
            this.appSelectChange($event, app, 'selfBuilt')
          }
        },
        {
          label: this.$t("module.userManage.thirdParty"),
          type: 'thirdParty',
          appList: [],
          loading: false,
          searchForm: {
            nameOrCode: ""
          },
          loadDataFun: () => {
            this.searchData('thirdParty', 1)
          },
          appSelectChange: ($event, app) => {
            this.appSelectChange($event, app, 'thirdParty')
          }
        }
      ]
    };
  },
  created() {
    this.selectAdd.selfBuiltApp = this.selectApp.filter(item => item.applicationType != 1)
    this.selectAdd.thirdPartyApp = this.selectApp.filter(item => item.applicationType == 1)
    this.searchData('selfBuilt', 0)
    this.searchData('thirdParty', 1)
  },
  mounted() {},
  methods: {
    appSelectChange(event, app, type) {
      if (type == 'selfBuilt') {
        if (event) {
          this.selectAdd.selfBuiltApp.push(app)
        } else {
          this.selectAdd.selfBuiltApp = this.selectAdd.selfBuiltApp.filter(tiem => tiem.applicationCode != app.applicationCode)
        }
      } else {
        if (event) {
          this.selectAdd.thirdPartyApp.push(app)
        } else {
          this.selectAdd.thirdPartyApp = this.selectAdd.thirdPartyApp.filter(tiem => tiem.applicationCode != app.applicationCode)
        }
      }
      this.selectAllotApp()
    },
    searchData(appType, index) {
      let appInfo = this.appInfo[index]
      if (appType == 'selfBuilt') {
        if (this.tenantCodeAndUser.tenantCode && this.tenantCodeAndUser.category) {
          appInfo.loading = true
          userManageAPI.getSelfBuiltApp({
            category:this.tenantCodeAndUser.category,
            tenantCode: this.tenantCodeAndUser.tenantCode,
            nameOrCode: appInfo.searchForm.nameOrCode
          }).then(res => {
            //过滤掉未分配的无效应用
            let allSelections = this.selectAdd.selfBuiltApp;
            let allSelectionIds = allSelections.map(a => a.applicationCode);
            const data = {
              recordList: res.filter(
                item => item.enabled == 1 || allSelectionIds.indexOf(item.applicationCode) != -1
              )
            };
            let defaultTypeList = [2, 3]
            // 平台管理员、租户管理员，新增时默认选中applicationType为2或者3数据，且不支持取消选中。 编辑时为兼容旧数据只将已选中数据中类型为2或者3的数据不支持取消选中
            if (this.tenantCodeAndUser.category == 1 || this.tenantCodeAndUser.category == 2) {
              data.recordList.forEach((item, index) => {
                if (defaultTypeList.includes(item.applicationType)) {
                  // 新增用户，选中所有类型为2，3的数据并置灰不可取消
                  if (!this.userInfo.id) {
                    item._checked = true;
                    item._disabled = true;
                    // 未选中任何应用和有选中的应用但不包含RIPPLES.crc时，把数字化应用设置为选中
                    let noRipples = allSelections.filter(
                      selection => selection.applicationCode == item.applicationCode
                    );
                    if (allSelections.length == 0 || !noRipples.length) {
                      allSelections.push(item);
                      this.selectAllotApp(item);
                    }
                  } else {
                    // 编辑用户 并且初始选中接口返回的数据中包含该数据并且该数据类型为2，3的情况下，置灰不可取消
                    if (this.defaultSelectApp.find(app => app.applicationCode == item.applicationCode)) {
                      item._checked = true;
                      item._disabled = true;
                      let noRipples = allSelections.filter(
                        selection => selection.applicationCode == item.applicationCode
                      );
                      if (!noRipples.length) {
                        allSelections.push(item);
                        this.selectAllotApp(item);
                      }
                    }
                  }
                }
              });
            }
            //排序,已选中的排在前面
            data.recordList = this.$root.$options.filters["checkedAppFirst"](data.recordList, allSelections);
            data.recordList.forEach((item, index) => {
              if (defaultTypeList.includes(item.applicationType)) {
                data.recordList.splice(index, 1);
                if (data.recordList[0] && data.recordList[0].applicationCode !== "RIPPLES.crc") {
                  data.recordList.unshift(item);
                } else {
                  data.recordList.splice(1, 0, item);
                }
              }
            })
            data.recordList.forEach(item => {
              if (allSelections.find(app => app.applicationCode == item.applicationCode) && !item._checked) {
                item._checked = true
              }
            })
            appInfo.appList = data.recordList
          }).finally(() => {
            appInfo.loading = false
          });
        } else {
          appInfo.appList = []
        }
      } else {
        appInfo.loading = true
         userManageAPI.getThirdPartyApp({
            code: 'THIRD_PARTY_APP',
            nameOrCode: appInfo.searchForm.nameOrCode
         }).then(res => {
            let result = {
                recordList: []
              },
              thirdAllSelections = this.selectAdd.thirdPartyApp,
              thirdAllSelectionIds = thirdAllSelections.map(t => t.applicationCode);
            res
              .filter(item => item.enabled == 1 || thirdAllSelectionIds.indexOf(item.thirdAllSelectionIds) != -1) //去掉未分配的无效应用
              .forEach(item => {
                result.recordList.push({
                  id: item.id,
                  applicationCode: item.vsiKey,
                  applicationName: item.vsiValue,
                  applicationType: 1,
                  topic: item.vsiDescription,
                  enabled: item.enabled
                });
              });
            //排序,已选中的排在前面
            result.recordList = this.$root.$options.filters["checkedAppFirst"](
              result.recordList,
              thirdAllSelections
            );
            result.recordList.forEach(item => {
              if (thirdAllSelections.find(app => app.applicationCode == item.applicationCode) && !item._checked) {
                item._checked = true
              }
            })
            appInfo.appList = result.recordList
          }).finally(() => {
            appInfo.loading = false
          });
      }

    },
    reset(sign) {
      // 自建应用or第三方应用的搜索
      this.$refs[sign][0].resetFields();
      this.search(sign);
    },
    // 自定义行样式-自建应用&第三方应用
    rowClassName(row) {
      // 自建应用&第三方应用：enabled：无效-0，有效-1。
      if (row.enabled == 0) {
        return "tableDisableStyle";
      }
      // // 自建应用：enabled：无效-0，有效-1，根据invalidSign存在判断为该应用在租户下已取消，也置灰。第三方应用：enabled：无效-0，有效-1
      // if (row.enabled == 0 || row.invalidSign) {
      //   return "tableDisableStyle";
      // }
    },
    // 选择自建应用 or 第三方应用
    selectAllotApp() {
      const newSelected = [...this.selectAdd.selfBuiltApp, ...this.selectAdd.thirdPartyApp]
      this.$emit("handleAllotApp", { selection: newSelected });
    }
  },
};
</script>

<style lang="less">
.AllotApp-page {
  .title {
    margin-bottom: 0px;
    border-bottom: none
  }
  .ivu-list-split .ivu-list-item {
    border-bottom: none
  }
  .select-App-list {
    height: 100%;
    border-left: 1px solid #D8D8D8;
    padding: 0 20px;
    .select-app {
      background: #F5F7FA;
      height: 400px;
      width: 100%;
      padding: 16px;
      overflow-y: auto;
      .title {
        font-size: 12px;
        color: #858B9C;
        font-weight: 400;
      }
      .app-name {
        font-size: 14px;
        color: #333333;
        font-weight: 400;
        
      }
      .select-icon {
        display: inline-block;
        width: 16px;
        height: 16px;
        position: relative;
        top: 0;
        left: 0;
        &::after {
          content: '';
          display: table;
          width: 4px;
          height: 8px;
          position: absolute;
          top: 4px;
          left: 5px;
          border: 2px solid #fff;
          border-top: 0;
          border-left: 0;
          -webkit-transform: rotate(45deg) scale(1);
          -ms-transform: rotate(45deg) scale(1);
          transform: rotate(45deg) scale(1);
          -webkit-transition: all .2s ease-in-out;
          transition: all .2s ease-in-out;
          border-color: #ff6f4b
        }
      }
    }
    .self-built-app {
      min-height: 100px;
    }
  }
  .ivu-form {
    .ivu-row {
      .ivu-col:nth-child(1) {
        .ivu-form-item {
          margin-bottom: 10px !important;
          .ivu-form-item-content {
            margin-right: 0px !important;
            width: 100% !important;
          }
        }
      }
      .ivu-col:nth-child(2) {
        .ivu-form-item {
          .ivu-form-item-content {
            padding-left: 10px !important;
            .ivu-btn-warning {
              margin-right: 8px !important;
            }
          }
        }
      }
    }
  }
}
// .AllotApp-page {
//   .title {
//     border-bottom: 1px solid #d8d8d8;
//     font-size: 14px;
//     font-weight: 700;
//     line-height: 40px;
//     margin-bottom: 20px;
//   }
//   .allot-app-wrap .ivu-table .ivu-table-header thead tr th:first-child {
//     padding-left: 0 !important;
//   }
//   .allot-app-wrap .ivu-table-cell-with-selection .ivu-checkbox-wrapper {
//     margin-left: 5px !important;
//   }
//   .dialog-cancel-tablestyle {
//     .table-bar {
//       margin: 0;
//     }
//     .single-table-con {
//       padding: 0;
//     }
//   }
// }
.allot-app-wrap {
  padding: 16px;
  border: 1px solid rgba(216,216,216,1);
  height: 400px;
  .serach-input {
    margin-bottom: 21px;
  }
  .app-list {
    max-height: calc(100% - 50px);
    overflow-y: auto;
  }
}
</style>